/*
 * Copyright (c) 2020, 2023, 3044483124@qq.com All rights reserved.
 *
 */
package dao.impl;

import dao.StudentDao;
import pojo.Student;

import javax.xml.crypto.Data;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Project: jdbc - Studentimpl
 * <p>Powered by jiangbo On 2023-02-14
 * 21:11:41
 * <p>Created by IntelliJ IDEA
 *
 * @author jiangbo [3044483124@qq.com]
 * @version 1.0
 * @since 8/17
 */
public class Studentimpl implements StudentDao {

    private Connection conn = null;
    private Statement st = null;
    private ResultSet rs = null;

    @Override
    public List<Student> findAll() {
        List<Student> list = new ArrayList<>();
        //1、注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/zhao?useUniCode=true&characterEncoding=utf8",
                    "root", "123456");
            //3、获取执行对象
            st = conn.createStatement();
            //4、编写执行的sql语句
            String sql = "select * from student";
            //获取结构
            rs = st.executeQuery(sql);
            //循环遍历存入list集合中
            while (rs.next()) {
                int sid = rs.getInt("sid");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                Date birthday = rs.getDate("birthday");
                Student stu = new Student();
                stu.setSid(sid);
                stu.setName(name);
                stu.setAge(age);
                stu.setBirthday(birthday);
                list.add(stu);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        //返回list集合
        return list;
    }
}


